﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace SharpSoft.Web.Authorize
{
    /// <summary>
    /// 替换默认的身份认证处理
    /// </summary>
    internal class CookieAuthenticationHandler : Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler
    {
        public CookieAuthenticationHandler(IOptionsMonitor<CookieAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        {
        }
        /// <summary>
        /// 指定一些Header,用于判断该请求是否通过是使用API的形式访问，
        /// 对于API形式的请求，用户认证的状态将使用ApiResult的形式反馈，否则跳转到相应的处理页面。
        /// </summary>
        public static string[] APIRequestHeaders = new string[] {
            "X-Requested-With"
        };
        protected override Task InitializeHandlerAsync()
        {
            return base.InitializeHandlerAsync();
        }
        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            var result = base.HandleAuthenticateAsync();
            return result;
        }
        protected override async Task HandleChallengeAsync(Microsoft.AspNetCore.Authentication.AuthenticationProperties properties)
        {//处理可疑用户 
            if (isxhr())
            {
                var msg = "您的身份已失效，请重新登录。";
                Response.StatusCode = 200;
                var json = JsonConvert.SerializeObject(new ApiResult(-401, msg));
                var da = Encoding.UTF8.GetBytes(json);
                Response.ContentLength = da.Length;
                Response.ContentType = "application/json;charset=utf-8";
                Response.Body.Write(da, 0, da.Length);
            }
            else
            {
                await base.HandleChallengeAsync(properties);
            }
        }

        bool isxhr()
        {
            if (APIRequestHeaders != null)
            {
                foreach (var item in APIRequestHeaders)
                {
                    if (this.Context.Request.Headers.ContainsKey(item))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        protected override async Task HandleForbiddenAsync(Microsoft.AspNetCore.Authentication.AuthenticationProperties properties)
        {//处理禁止访问
            if (isxhr())
            {

                var msg = "您无权进行此操作。";
                Response.StatusCode = 200;
                var json = JsonConvert.SerializeObject(new ApiResult(-403, msg));
                var da = Encoding.UTF8.GetBytes(json);
                Response.ContentLength = da.Length;
                Response.ContentType = "application/json;charset=utf-8";
                Response.Body.Write(da, 0, da.Length);
            }
            else
            {
                await base.HandleForbiddenAsync(properties);
            }

        }

        protected async override Task HandleSignInAsync(ClaimsPrincipal user, Microsoft.AspNetCore.Authentication.AuthenticationProperties properties)
        {
            await base.HandleSignInAsync(user, properties);
        }

        protected async override Task HandleSignOutAsync(AuthenticationProperties properties)
        {
            await base.HandleSignOutAsync(properties);
        }
    }
}
